/*
 * Copyright 2008 Carnegie Mellon University
 * Licensed under the Apache License, Version 2.0 (the "License"); 
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *  
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, 
 * software distributed under the License is distributed on an
 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
 * KIND, either express or implied. See the License for the
 * specific language governing permissions and limitations
 * under the License.
 */

var lastPoolId;
var lastTopicId;
var topics;
var judgments;
var startTime;

function init() {
  lastPoolId = getCookie(taskNameShort+".ir.lastPoolId");
  lastTopicId = getCookie(taskNameShort+".ir.lastTopicId");
  
  // Temp
  if (lastPoolId==-1) { lastPoolId  = getCookie("lastPoolId"); }
  if (lastTopicId==-1) {lastTopicId = getCookie("lastTopicId"); }
  
  document.title = 'SEPIA: '+msg( lang, 'msg_he_ir' );
  loadHeaderSubSub( lang );
  loadTopicList("IREvalTopics");
  loadPoolList("IREvalPools");
  loadLabelButtons();
  loadMessages(lang);
  if ( lastTopicId ) {
  topicSelected(lastTopicId);
  }
}

function topicSelected(externalId) {
  if ( !externalId || externalId==-1 ) return;//in case blank selected
    $('main_block').style.display = 'none';
    
  //init highlight
    var currentTopicIndex = 0; 
    for (var i = 0; i < topics.length; i++) {
      if (externalId == topics[i].externalId) {
        currentTopicIndex = i;
        break;
      }
    }
  loadTopicIntoHTML(topics[currentTopicIndex]);
  $('highlight').value = topics[currentTopicIndex].title;
  
  lastTopicId = externalId;
  setCookie(taskNameShort+".ir.lastTopicId",lastTopicId);
    if ( lastPoolId ) {
      topicAndPoolSelected( lastTopicId, lastPoolId );
    }
}

function topicAndPoolSelected(externalId, poolId) {
  if ( !externalId || externalId==-1 || !poolId || poolId==-1 ) return;//in case blank selected
  $('loading').style.display = '';    
  $('main_block').style.display = 'none';

  loadDocs(externalId, poolId, "score");
   
   lastPoolId = poolId;
   setCookie(taskNameShort+".ir.lastPoolId",lastPoolId);
   
   $('loading').style.display = 'none';
   $('main_block').style.display = '';
   jQuery("#footer").bottom();
   
   preemptiveLoading(-1);
}

function docSelected( docId ) {
  if ( !docId || docId == -1 ) return;//in case blank selected
  
  //delete previous doc's content for avoiding using up memory
  if ($('docId').value) {
    var previousIndex = findIndex($('docId').value);
    if (0<=previousIndex && previousIndex<judgments.length) {
      judgments[previousIndex].doc_content = "";
    }
  }
  
  $('docId').value = docId;
  for (var i=0; i<irLabels.length; i++) {
    $(irLabels[i]).checked = false;
  }
  
  var currentDocIndex = findIndex(docId);
  var judgment = judgments[currentDocIndex];
  
  if (judgment) {
    if (!judgment.doc_content) {
      var param = eval('$H({"action": "IREvalGetDoc", "docId": "'+docId+'"})').toQueryString();//userId in session
      var json = sync(param);
      judgment.doc_content = json.document;
    }
    $('docContent').innerHTML = judgment.doc_content;
    $('originalDocContent').innerHTML = judgment.doc_content;
    highlight();
    
    var j = judgment.judgment;
    if ( j && $(j) ) {
      $(j).checked = true;
    }
    $('evidence').value = ues(judgment.evidence);
    $('doc_block').style.display = '';
    jQuery("#footer").bottom();
  }
  startTime = new Date().getTime();
  preemptiveLoading(currentDocIndex);
}

function loadDocs( externalId, poolId, sortingCriteria ) {
  if ( !externalId || externalId==-1 || !poolId || poolId==-1 ) return;
  $('doc_block').style.display = 'none';
  
  var list = $('docList');
  initList(list);
    
  var param = [];
  param.action = "IREvalDocList";
  param.poolId = poolId;
  param.externalId = externalId;
  param.sortingCriteria = sortingCriteria;
  var json = sync(param);
  judgments = json.ir_judgments;
  resetList(list);
  for (var i = 0; i < judgments.length; i++) {
    var done = judgmentToDone(judgments[i]);
    var opt = document.createElement("option");
    var id = judgments[i].doc_id;
    opt.value = id;
    opt.id = "doc_"+id;
    var str = document.createTextNode(done+id);
    opt.appendChild(str);
    list.appendChild( opt );
  }
}

function saveAndGoNext() {
  var externalId = $('externalId').value;
  var docId = $('docId').value;
  var evidence = $('evidence').value;
  var judgment = "";
  var atLeastOneChecked = 0;
  for (var i=0; i<irLabels.length; i++) {
    if ( $(irLabels[i]) && $(irLabels[i]).checked ) {
      judgment = $(irLabels[i]).value;
      atLeastOneChecked = 1;
      break;
    }
  }
  if (! atLeastOneChecked ) {
    alert("Please make a relevance judgment");
    return;
  }  
  //Validate
//  if ( judgment && judgment!="L0" && !evidence ) {
//    alert("Please fill in the evidence!");
//    return;
//  }
  
  var time = new Date().getTime() - startTime;
  startTime = 0; // init just in case
  
  //Save into remote
  var param = [];
  param.action = "IREvalUpdate";
  param.externalId = externalId;
  param.docId = docId;
  param.judgment = judgment;
  param.evidence = es(evidence);
  param.time = time;
  sync(param);
  showMessage( msg_suc_ireval_save );
    
  //Save into local obj
  var currentDocIndex = findIndex( docId );
  var j = judgments[currentDocIndex];
  j.judgment = judgment;
  j.evidence = evidence;
  $('doc_'+docId).innerHTML = judgmentToDone(j)+docId;
    
  goToNext( currentDocIndex );
}

function goToNext( currentIndex ) {
    for (var i = currentIndex+1; i < judgments.length; i++) {
    if ( !judgments[i].judgment && !(judgments[i].evaluated_by_others>0) ) {
      $('docList')[i+1].selected = true; // make sure list selection is made
      docSelected( judgments[i].doc_id );//load content
      break;
    }
    }
}

function findIndex(docId) {
    for (var i = 0; i < judgments.length; i++) {
    if (docId==judgments[i].doc_id) {
      return i;
    }
    }
  return -1;
}

function highlight() {
  var text = $('originalDocContent').innerHTML;
  if (!text){ return; }
  var words = $('highlight').value.replace(/[ 　]/g, " ").split(" ");
    var i=0;
    for (i=0; i<words.length; i++) {
        if( words[i] != "" ) {
          var rgexp = new RegExp(words[i], "g");
            text = text.replace(rgexp, '<strong>'+words[i]+'</strong>');
        }
    }
    $('docContent').innerHTML = text;
}

function judgmentToDone( j ) {
  var done = "";
  if (j.judgment) {
    done += "["+j.judgment+"] ";
  }
  if ( j.evaluated_by_others > 0 ) {
    done += "[x] ";
  }
  return done;
}

function preemptiveLoading( currentIndex ) {
  var count = 0;
  var max = 4;
    for (var i = currentIndex+1; i < judgments.length; i++) {
    if ( !judgments[i].judgment && !(judgments[i].evaluated_by_others>0) ) {
      if (count++>max) {
        break;
      }
      if (judgments[i].doc_content) {
        continue;
      }
      var param = eval('$H({"action": "IREvalGetDoc", "docId": "'+judgments[i].doc_id+'", "index": "'+i+'"})').toQueryString();
      new Ajax.Request( jsonPath, {
            method: "get",
            asynchronous: true,
            parameters: param, 
            onComplete: setContent
        } );
      }
    }
}

function setContent( originalRequest ) {
  var json = eval("(" + originalRequest.responseText + ")");
  judgments[json.index].doc_content = json.document;
}

function loadLabelButtons() {
  for (var i=0; i<irLabels.length; i++) {
    var item = document.createElement("input");
    item.type = "radio";
    item.name = "judgment";
    item.id = irLabels[i];
    item.value = irLabels[i];
    var htmlLabel = document.createElement("label");
    htmlLabel.id = "relevance_label_"+i;
    htmlLabel.title = "Shortcut: ALT+"+(i+1);
    htmlLabel.htmlFor = irLabels[i];
    var str = document.createTextNode(irLabels[i]+"    "); //+" ("+labelDescs[i]+")  "
    htmlLabel.appendChild( str );
    $('labelArea').appendChild( item );
    $('labelArea').appendChild( htmlLabel );
  }
}

// Shortcut
document.observe('keydown', function(e) {
  if (!e.altKey) return;
  var keycode;
  if (window.event) {
    keycode = window.event.keyCode;
  } else {
    keycode = e.which;
    // 2 and numpad 2
  }
  
  var pressed = false;
  var keycodes1 = [49,50,51,52,53,54,55,56,57,48]; //0-9
  var keycodes2 = [97,98,99,100,101,102,103,104,105,96]; //0-9 in keypad
  for (var i=0; i<irLabels.length; i++) {
    if (i>=keycodes1.length) {break;}
    if (keycode==keycodes1[i] || keycode==keycodes2[i] ) { // 2
      $(irLabels[i]).checked = true;
      pressed = true;
      break;
    }
  }
  if (pressed) {
    $('saveAndGoNext').click();
  }
});

var evidenceText = "";
jQuery(document).ready(function() {
  jQuery('.doc').bind('mouseup', function(e) {
    var selectedRange = getSelectedRange();
    var selectedText = selectedRange.toString();
    evidenceText = selectedText;
    if (selectedText) {
      if ( e.which <= 1 ) { //left click only
        var l = e.pageX;
        var t = e.pageY;
        setTimeout(function(e){ // this trick is needed for IE!!
          if (getSelectedText()) { // unless this checking, pop-up occurs without text selection when clicked on a selection
            jQuery('#command_list').css('left', l+'px').css('top', t+'px');
            jQuery('#command_list').fadeIn('fast');
          }
        }, 10);
      }
    }
  });
  
  jQuery('#command_copy').mouseup( function() {
    $("evidence").value += ($("evidence").value?'<>':'')+evidenceText.replace(/(\r)?\n/g,'');
    jQuery('#command_list').offset({ top: 0, left: 0 }).hide(); //hideCommandList
  });
  
  jQuery('.doc').bind('mousedown', function(e) {
    jQuery('#command_list').offset({ top: 0, left: 0 }).hide(); //hideCommandList
  });
  
  jQuery('a', '#command_list').button();
  
  jQuery('#toggle').click( function () {
    jQuery('#togglable1').slideToggle('fast');
    jQuery('#togglable2').slideToggle('fast');
  });
});